import React from 'react';
import { NewGuid, debounce } from 'ronds-react-ui/es/utils';
import ResizeSensor from 'css-element-queries/src/ResizeSensor';

(window as any).RzGrapheOpenLogger = false;
// 隐藏特征频率
(window as any).disableCharacteristicFrequency = false;
(window as any).closeGraphThemeBtn = true;

// 动态加载graph
export const loadGraph = (jslibs: string[], callBack: () => void, onError: (lib: string, ex: any) => void) => {
  if (!jslibs || jslibs.length === 0) {
    jslibs = [
      './rzgraph/rzgraph/jquery.min.js',
      './rzgraph/rzgraph/js/highstock.js',
      './rzgraph/rzgraph/js/highcharts-more.js',
      './rzgraph/rzgraph/js/highcharts-3d.js',
      './rzgraph/rzgraph/js/theme.js',
      './rzgraph/rzgraph.min(3).js',
    ];
  }
  // 动态加载图形组件
  const loadJs = (index: number) => {
    if (index >= jslibs.length) {
      setTimeout(() => {
        callBack();
      }, 100);
      return;
    }
    // clearconsole.log('sss', jslibs, index);
    const id = jslibs[index].replace(/\//g, '').replace('.', '');
    if (document.getElementById(id)) {
      loadJs((index += 1));
    } else {
      const script = document.createElement('script');
      script.id = id;
      script.type = 'text/javascript';
      // script.crossOrigin = '';
      script.src = jslibs[index];
      script.onload = () => {
        loadJs((index += 1));
      };
      script.onerror = (ex) => {
        onError && onError(jslibs[index], ex);
      };
      // 这里需要加到body下 head里面第一次可能取不出来值
      document.body.appendChild(script);
    }
  };
  /** 加载图谱的库 */
  const loadJsLib = () => {
    if ((window as any).rzgraph) {
      callBack();
      return;
    }
    loadJs(0);
  };
  return loadJsLib();
};

/**
 * 枚举 默认游标位置
 *
 * @export
 * @enum {number}
 */
export const DefaultCurosrPosition = {
  // 默认第一个
  First: '0',
  // 默认最后一个
  Last: '1',
  // 默认中间
  Center: '2',
  // 不加载游标
  None: '3',
};

interface IBaseChartProps {
  chartData: any[];
  chartConfig?: any;
  getChart?: (_chart: any) => void;
  onMainCursorMoved?: (selectedX: number, selectedY: number, data?: any, args?: any, sourceData?: any) => void;
  onRenderEnd?: () => void;
  onSetExtremes?: (min: number, max: number) => boolean;
}

const BaseChart = (props: IBaseChartProps) => {
  const { chartData, chartConfig, getChart, onMainCursorMoved, onRenderEnd, onSetExtremes } = props;

  // 判断是否为首次渲染
  const firstRender = React.useRef<boolean>(true);

  const divId: string = React.useMemo(() => {
    return `graph_${NewGuid()}`;
  }, []);

  const onResize = () => {
    if (chartRef.current !== null) {
      try {
        console.log('onResize');
        chartRef.current.Resize();
      } catch (ex) {
        console.log(ex);
      }
    }
  };

  const onResizeStrategy = React.useMemo(() => {
    return debounce(onResize, 200, false);
  }, []);

  const chartRef = React.useRef<any>(null);

  // 初始化
  const init = () => {
    if ((window as any).rzgraph) {
      let resizeSensor = null;
      const element = document.getElementById(divId);
      resizeSensor = new ResizeSensor(element as any, onResizeStrategy);

      const chart = new (window as any).rzgraph.CommonChart(divId, DefaultCurosrPosition.Last, {
        onMainCursorMoved: (selectedX: number, selectedY: number, data: any, args: string): void => {
          onMainCursorMoved && onMainCursorMoved(selectedX, selectedY, data, args);
        },
        onRenderEnd: () => {
          onRenderEnd && onRenderEnd();
        },
        onSetExtremes: (min: number, max: number) => {
          let b = true;
          if (onSetExtremes) {
            b = onSetExtremes(min, max);
          }
          return b;
        },
      });

      // 这里是初始化图片上的帮助信息 CurosrValue是个特殊值 填了的话 会出现游标值 内部自动更新
      chart.layout._InitHelperInfo({
        chartName: '测点1',
        // CurosrValue: '',
      });

      // 这里是删除内置的菜单 如果不要的话
      chart.menuInstance.RemoveMenuItem('LockChart');

      // 这里是添加自定义的菜单
      chart.menuInstance.AddMenuItem('alarmLine', '修改标注', function () {
        console.log('这里是添加自定义的菜单');
        chart.HideOrShowAlarmLine(false);
        // showAlarmLine = !showAlarmLine;
      });

      chart.layout.generateToolbox = true;

      chart.layout.generateHelperinfo = true;

      chart.chartConfig.xIsTime = true;

      chart.chartConfig.isAllowMaxBtn = true;

      if (chartConfig) {
        Object.keys(chartConfig).forEach((p) => {
          chart.chartConfig[p] = chartConfig[p];
        });
      }

      // const cursor = new (window as any).rzgraph.DoubleCursor(chart);
      // chart.registeredCursor([cursor]);

      chart.Init();

      // 如果chartData 存在渲染数据
      if (chartData) {
        chart.render(chartData, '', '');
        firstRender.current = false;
      }

      chartRef.current = chart;
      getChart && getChart(chart);
    }
  };

  React.useEffect(() => {
    loadGraph(
      [],
      () => {
        init();
      },
      () => {
        console.warn('loadGraph 加载失败');
      }
    );
    return () => {
      if (chartRef.current !== null) {
        chartRef.current.Dispose();
        chartRef.current = null;
      }
    };
  }, [divId, chartConfig]);

  React.useEffect(() => {
    console.log(chartRef.current);
    console.log(chartData);
    if (firstRender.current && chartRef.current !== null && chartData) {
      chartRef.current.render(chartData, '', '');
      firstRender.current = false;
    }
  }, [chartData]);

  return (
    <div
      id={divId}
      style={{
        height: '100%',
        width: '100%',
        overflow: 'hidden',
      }}
      className="RZGraphDiv"
    />
  );
};

export default BaseChart;
